package dyu.Questionnaire;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Button;
import android.content.Intent;
import android.view.Window;


public class QuestionGroup extends ListActivity{
	int groupNumber=1;
	int numOfQuestions=0;
	String[] questionsList, answerList, answerResult;
	android.app.AlertDialog dlg, dlgMessage;
	Button butSubmit, butCancel;
	String choosenAns;
	ListView mainLV;
	
			
			
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);		
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		//setContentView(R.layout.questionlistitem);
		Bundle extras = getIntent().getExtras();
		
		
		if(extras!=null){
			String temp = extras.getString("questionNumber");
			this.groupNumber = Integer.parseInt(temp);
		}
		
		int group_ID=this.getResources().getIdentifier("Group" + this.groupNumber + "_Question", "array", this.getPackageName());
		if(group_ID!=0){			
			 String [] temp = getResources().getStringArray(group_ID);

			questionsList  = new  String[temp.length-1];
			for(int  i=1; i<temp.length;i++) questionsList[i-1] = temp[i];
			this.numOfQuestions = this.questionsList.length;
			this.answerResult = new String[this.numOfQuestions];
			for(int i=0;i<answerResult.length;i++) this.answerResult[i] = "";
			//setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked, questionsList));
			ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.questionlistitem,R.id.text1,questionsList);
			this.setListAdapter(adapter);
			this.mainLV = this.getListView();
			this.mainLV.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);			
			//this.mainLV.setLayoutParams(android.R.layout.simple_list_item_checkedLayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));		
		}		
	}
	
	public void onListItemClick(ListView parent, View v, int position, long id){
		
		int ans_position=getResources().getIdentifier("Group" + this.groupNumber + "_Answer" + (position + 1), "array", this.getPackageName());
		
		if(ans_position!=0)
		{				
			answerList= getResources().getStringArray(ans_position);			
			this.CreateDiaglogAnswer(questionsList[position], position);	
			
		}
		else
		{
			//announce that there is no answer for this question
			this.CreateDialogMessage("這個問題裡沒有答案選項");
			
		}
	}
	
	private void CreateDialogMessage(String message){
		if(this.dlgMessage!=null) this.dlgMessage.dismiss();
		
		this.dlgMessage = new AlertDialog.Builder(this)
        .setTitle("注意!")       
        .setNegativeButton("關閉", null)               
        .setMessage(message)        
        .create();     
		
		this.dlgMessage.show();
		
	}
		
	private void CreateDiaglogAnswer(final String questionText, final int question){		
		if(this.dlg!=null) this.dlg.dismiss();
		
		int selected = -1;
		choosenAns=answerResult[question];
		if(this.answerResult[question] != ""){			
			char res_char = this.answerResult[question].charAt(0);
			res_char -= 65;
			selected = res_char;			
		}
			
		this.dlg = new AlertDialog.Builder(this)
		//.setIcon(R.drawable.icon)        
		.setTitle(questionText)
        .setSingleChoiceItems(answerList, selected, new DialogInterface.OnClickListener() {
			
			public void onClick(DialogInterface dialog, int position) {
				// TODO Auto-generated method stub										
				int ans=position + 65; //A + index of the answer					
				choosenAns = Character.toString((char)ans);
				//Toast.makeText(getBaseContext(), choosenAns , Toast.LENGTH_SHORT).show();					
			}

		})
		.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) 
            {
            	//input answer into answerResult list  
            	if( choosenAns!=""){     	
	            	answerResult[question]=choosenAns;
	            	mainLV.setItemChecked(question, true);
            	}
            	else{
            		//notify to user to chose answer
            		CreateDialogMessage("這個問題尚未回答!");   
            		//dlg.show();
            		//CreateDiaglogAnswer(questionText, question);
            		mainLV.setItemChecked(question, false);
            		
            	}
            
           }
        })
        
        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				if(!CheckIfAlreadyAnswered(question))
					mainLV.setItemChecked(question, false);
				else 
					mainLV.setItemChecked(question, true);
					
			}
		})                   
        
        .create();     
		
		this.dlg.show();
	}
		
	//--- Submit Dialog appear when user press back button ---//
	private void CreateDiaglogSubmit(String SubmitText){		
		if(this.dlg!=null) this.dlg.dismiss();
		
		this.dlg = new AlertDialog.Builder(this)
		//.setIcon(R.drawable.icon)        
		.setTitle(SubmitText)
        .setPositiveButton("發送", new DialogInterface.OnClickListener() {  
            public void onClick(DialogInterface dialog, int whichButton) 
            {
            	if(CheckIfFinishAnswer()){
            		DoSubmitResult();            		
            	}
            	else{
            		//show message error: "not finished answering questions"
            		CreateDialogMessage("請完成所有問題!");
            		return;
            		//highlight the next not be finished question
            	}
            
           }
        })
        .setNegativeButton(" 繼續填寫", null)                   
        .show();
	}
	
	private boolean CheckIfAlreadyAnswered(int question){
		if(this.answerResult[question]!="")
			return true;
		
		return false;
	}
	
	private boolean CheckIfFinishAnswer(){
		for(int i=0;i<this.answerResult.length;i++){
			if(this.answerResult[i]=="")
				return false;
		}
		return true;
	}
	
	private String MakeStringAnswer(){
		String result = "G" + this.groupNumber + "||";
		for(int i=0; i<this.answerResult.length; i++)
			result += this.answerResult[i];
				
		return result;
	}
	
	//--- onClickListenner when clicking Back button ---//
	public void onBackPressed() {
		 this.CreateDiaglogSubmit("發送?");
		  
		}
	
	//---Disable Home button ---///
	public void onAttachedToWindow() {
	    this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
	    super.onAttachedToWindow();
	    
	}

	//--- Create Option Menu ---//
	public boolean onCreateOptionsMenu(Menu menu){
		super.onCreateOptionsMenu(menu);
		menu.add(0, 0, 0, "發送").setIcon(R.drawable.ic_menu_submit);
		menu.add(0,1,0,"返回").setIcon(R.drawable.ic_menu_back);
		menu.add(0,2,0,"離開").setIcon(R.drawable.ic_menu_exit);
		return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item){
		switch(item.getItemId()){
		case 0:
			if(CheckIfFinishAnswer()){
        		this.DoSubmitResult();
        	}
        	else{
        		//show message error: "not finished answering questions"
        		CreateDialogMessage("請完成所有問題!");
        		
        	}
        	
			return true;
		case 1:
			
			finish();
			return true;
		case 2:
			moveTaskToBack(true);		
			Intent intentOfService = new Intent(getBaseContext(), MyService.class);
			Bundle extras = new Bundle();
			extras.putString("timeCalled", "time started");
			intentOfService.putExtras(extras);
        	this.startService(intentOfService);
			return true;
			
		}
		return false;
		
	}
	
	private void DoSubmitResult(){
		Intent data = new Intent();      
		String result = MakeStringAnswer();
		data.putExtra("AnswerResult", result);
		data.putExtra("G_Number", "" + this.groupNumber);		
		setResult(RESULT_OK, data);
		finish();
	}
}
